package com.yixiu.os.win;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class CmdHelper {

    /**
     * 执行win的cmd命令
     * @param commandStr
     * @return
     */
    public static String exeCmd(String commandStr) {
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            System.out.println(sb.toString());
            int index = sb.toString().indexOf("error");
            if(index >= 0) {
                return sb.substring(index);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "error:" + e.getMessage();
        }
        finally
        {
            if (br != null)
            {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }






    public static void main(String[] args) {
        String commandStr = "ping www.taobao.com";
        //String commandStr = "ipconfig";
        CmdHelper.exeCmd(commandStr);
    }




}




